﻿namespace _5_NovaAdmin.Infrastructure.Redis;

public class RedisClient
{
    private readonly Lazy<ConnectionMultiplexer> _lazyConnection;
    //private readonly IRedisConfigOptions _config;
    private readonly dynamic _config;

    public RedisClient(dynamic config)
    {
        _config = config;

        _lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            var configurationOptions = new ConfigurationOptions
            {
                EndPoints = { $"{_config.Host}:{_config.Port}" },
                Password = _config.Password,
                Ssl = _config.Ssl is bool ssl ? ssl : false,
                AbortOnConnectFail = _config.AbortOnConnectFail is bool abort ? abort : false,
                ConnectTimeout = _config.ConnectTimeout is int time ? time : 5000,
                ConnectRetry = _config.ConnectRetry is int retry ? retry : 3
            };

            return ConnectionMultiplexer.Connect(configurationOptions.ToString());
        });
    }

    public StackExchange.Redis.IDatabase GetDatabase() => _lazyConnection.Value.GetDatabase(_config.Database is int db ? db : -1);

    public StackExchange.Redis.ISubscriber GetSubscriber() => _lazyConnection.Value.GetSubscriber();

    public ConnectionMultiplexer GetConnection() => _lazyConnection.Value;
}
